<?php
/**
 * soap Request Base
 */

namespace dragon\Request\Base;

use dragon\Contract\Request;
use dragon\Exceptions\RequestException;
use think\Log;

class SoapRequest
{
    protected $url = 'http://192.168.1.190:1001/PlantFormService.asmx?WSDL';

    public function run(Request $request, $options = []) {
        try {
            $params = $request->getParams();
            if(!$this->checkApiUrl($this->url)) throw new \SoapFault('400', '接口连接失败');

            $soapClient = new \SoapClient($this->url);

            $this->log('Params', $params);
            $result = $soapClient->__call($request->getApiMethodName(), array($params));
            $result = $result->{$request->getApiMethodName().'Result'};

            $this->log('Result', $result);

            $request->setStatusCode(200);
            $request->setResponse($result);
        } catch (\SoapFault $e) {
            $this->log('Error', $e->getMessage());
            $request->setStatusCode($e->getCode());
            $request->setMessage($e->getMessage());

            throw new RequestException($e->getMessage());
        }

        return $request;
    }


    /**
     * 验证接口地址是否可用
     * @param $url
     * @param int $timeout
     * @return bool
     */
    protected function checkApiUrl($url, $timeout = 3){

        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $url);
        curl_setopt($handle, CURLOPT_NOBODY, true);
        curl_setopt($handle, CURLOPT_TIMEOUT, $timeout);//设置默认超时时间为3秒
        $result = curl_exec($handle);

        return (boolean)$result;
    }

    protected function log($type, $content) {
        !is_scalar($content) and $content = json_encode_cn($content);
        $content = date('Y-m-d H:i:s | ').$type.': '.$content;
        $content .= "\r\n";
        file_rput_contents(RUNTIME_PATH.'/soap_log/'.date('Ym/d').'.log', $content, FILE_APPEND);
    }
}